package com.pks.datacenter.controller.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.pks.datacenter.aspect.AspectLogTag;
import com.pks.datacenter.entity.api.ApiField;
import com.pks.datacenter.entity.api.ApiMethod;
import com.pks.datacenter.entity.api.ApiPerm;
import com.pks.datacenter.entity.basic.DbField;
import com.pks.datacenter.entity.basic.DbInfo;
import com.pks.datacenter.entity.basic.DbSource;
import com.pks.datacenter.entity.basic.Tag;
import com.pks.datacenter.handler.RedisHandler;
import com.pks.datacenter.service.api.ApiFieldService;
import com.pks.datacenter.service.api.ApiMethodService;
import com.pks.datacenter.service.api.ApiPermService;
import com.pks.datacenter.service.basic.DbFieldService;
import com.pks.datacenter.service.basic.DbInfoService;
import com.pks.datacenter.service.basic.DbSourceService;
import com.pks.datacenter.service.basic.TagService;
import com.pks.resultful.common.SRemoteResult;
import com.pks.util.UtilConvert;
import com.pks.util.UtilString;
import com.pks.web.springmvc.controller.BasicController;


@RestController
@RequestMapping(value = "/apiMethod")
@Scope("prototype")
@Component("apiMethodController")
@Api(tags = "数据源对外接口")
public class ApiMethodController extends BasicController {

	@Resource
	private ApiMethodService apiMethodService;
	@Resource
	private DbInfoService dbInfoService;
	@Resource
	private ApiFieldService apiFieldService;
	@Resource
	private ApiPermService apiPermService;
	@Resource
	private RedisHandler redisHandler;
	@Resource
	private DbFieldService dbFieldService;
	@Resource
	private TagService tagService;
	@Resource
	private DbSourceService dbSourceService;

	@AspectLogTag(operType = "删除")
	@ApiOperation(value = "删除记录")
	@RequestMapping(value = "/delete" , method = RequestMethod.POST)
	public SRemoteResult<String> delete(HttpServletRequest request, String ids) {
		if (UtilString.isBlank(ids)) {
			return SRemoteResult.initErrorParamBlank(null);
		}
		if (StringUtils.isBlank(ids) || !ids.matches("^[0-9]+(,[0-9]+)*$")) {
			return SRemoteResult.initErrorParamInvalid(null);
		}
		List<Long> idList = UtilConvert.string2LongList(ids);
		apiMethodService.deleteApiMethods(idList);
		return SRemoteResult.initSuccess(null);
	}
	
	@AspectLogTag(operType = "修改")
	@ApiOperation(value = "新增或修改")
	@RequestMapping(value = "/modify" , method = RequestMethod.POST)
	public SRemoteResult<String> modify(HttpServletRequest request, ApiMethod obj , String apiFieldsJson) {
		if (obj == null) {
			return SRemoteResult.initErrorParamMissing(null);
		}
		if (obj.getDbId() == null) {
			return SRemoteResult.initError("对应数据源不能为空");
		}
		return apiMethodService.insertOrModify(obj,apiFieldsJson);
	}
	
	@AspectLogTag(operType = "复制")
	@ApiOperation(value = "复制")
	@RequestMapping(value = "/copy" , method = RequestMethod.POST)
	public SRemoteResult<String> copy(HttpServletRequest request, Long id) {
		if (id == null) {
			return SRemoteResult.initErrorParamMissing(null);
		}
		try {
			return apiMethodService.insertByCopy(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SRemoteResult.initError("复制失败");
	}
	
	
	

	@ApiOperation(value = "获取详情")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id",value = "id", dataType = "long" , paramType = "query" )
	})
	@RequestMapping(value = "/get" , method = RequestMethod.GET)
	public SRemoteResult<ApiMethod> findInfo(HttpServletRequest request, Long id) {
		if (id == null) {
			return SRemoteResult.initErrorParamMissing(null);
		}
		ApiMethod obj = apiMethodService.findById(id);
		if (obj == null) {
			return SRemoteResult.initErrorDataNone();
		} else {
			if (obj.getDbId() != null) {
				DbInfo dbInfo = dbInfoService.findById(obj.getDbId());
				if (dbInfo != null)  {
					obj.setShow_dbName(dbInfo.getName());
				}
			}
			List<ApiField> apiFieldList = apiFieldService.find("orders", apiFieldService.initQbuilder("apiId", obj.getId()), null);
			obj.setShow_apiFieldList(apiFieldList);
		}
		return SRemoteResult.initSuccess(obj);
	}

	@ApiOperation(value = "列表查询")
	@RequestMapping(value = "/list" , method = RequestMethod.POST)
	public SRemoteResult<List<ApiMethod>> list(HttpServletRequest request,Long tagId,Long dbId,Integer type,String apiName ,String apiNameLike ,String methodName ,String methodNameLike ,Integer state) {
		Map<String, Object> qbuilder = new HashMap<String, Object>();
		if (tagId != null) {
			qbuilder.put("tagId", tagId);
		}
		if (dbId != null) {
			qbuilder.put("dbId", dbId);
		}
		if (type != null) {
			qbuilder.put("type", type);
		}
		if (UtilString.isNotBlank(apiName)) {
			qbuilder.put("apiName", apiName);
		}
		if (UtilString.isNotBlank(apiNameLike)) {
			qbuilder.put("apiNameLike", "%" + apiNameLike.trim() + "%");
		}
		if (UtilString.isNotBlank(methodName)) {
			qbuilder.put("methodName", methodName);
		}
		if (UtilString.isNotBlank(methodNameLike)) {
			qbuilder.put("methodNameLike", "%" + methodNameLike.trim() + "%");
		}
		if (state != null) {
			qbuilder.put("state", state);
		}
		List<ApiMethod> list = new ArrayList<ApiMethod>();
		int total = 0;
		total = apiMethodService.getTotalRows(qbuilder);
		if (total > 0) {
			list = apiMethodService.findByPage(null, qbuilder);
			Map<Long, Tag> tagMap = tagService.findTagMap(Tag.TYPE_APIMETHOD);
			List<Long> dbIds = new ArrayList<Long>();
			for (ApiMethod obj : list) {
				if (obj.getDbId() != null) {
					dbIds.add(obj.getDbId());
				}
			}
			Map<Long, DbInfo> dbInfoMap = new HashMap<Long, DbInfo>();
			if (dbIds != null) {
				List<DbInfo> dbInfoList = dbInfoService.find(null, dbInfoService.initQbuilder("ids", dbIds), null);
				for (DbInfo dbInfo : dbInfoList) {
					dbInfoMap.put(dbInfo.getId(), dbInfo);
				}
			}
			for (ApiMethod obj : list) {
				if (obj.getDbId() != null && dbInfoMap.containsKey(obj.getDbId())) {
					obj.setShow_dbName(dbInfoMap.get(obj.getDbId()).getName());
				}
				if (obj.getTagId() != null) {
					Tag tag = tagMap.get(obj.getTagId());
					if (tag != null) {
						obj.setShow_tagName(tag.getName());
					}
				}
			}
		}
		return SRemoteResult.initPageList(list, total);
	}


    @ApiOperation(value = "数据查询（不分页）")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "apiName",value = "接口名称", dataType = "String" , paramType = "query" )
        ,@ApiImplicitParam(name = "state",value = "是否开启  1-是  0-否", dataType = "Integer" , paramType = "query" )
    })
    @RequestMapping(value = "/data" , method = RequestMethod.POST)
    public SRemoteResult<List<ApiMethod>> data(HttpServletRequest request,String apiName ,Integer state  ) {
        Map<String, Object> qbuilder = new HashMap<String, Object>();
        if (UtilString.isNotBlank(apiName)) {
            qbuilder.put("apiName", apiName);
        }
        if (state != null) {
            qbuilder.put("state", state);
        }
        List<ApiMethod> list = new ArrayList<ApiMethod>();
        list = apiMethodService.find(null, qbuilder, null);
        return SRemoteResult.initPageList(list, null);
    }

    // 获取带有接口权限信息的接口列表
    @RequestMapping(value = "listByApiPerm")
    public SRemoteResult<List<ApiMethod>> listByApiUserPerm(String apiNameLike,String methodNameLike,Long apiUserId,Integer permState) {
    	if (apiUserId == null) {
    		return SRemoteResult.initErrorParamMissing("接口账号ID");
		}
    	Map<String, Object> qbuilder = new HashMap<String, Object>();
    	if (UtilString.isNotBlank(apiNameLike)) {
			qbuilder.put("apiNameLike", "%" + apiNameLike.trim() + "%");
		}
    	if (UtilString.isNotBlank(methodNameLike)) {
			qbuilder.put("methodNameLike", "%" + methodNameLike.trim() + "%");
		}
    	if (permState != null && apiUserId != null && (permState == 1 || permState == 0 )) {
    		Map<String,Object> permMap = new HashMap<String, Object>();
    		permMap.put("apiUserId", apiUserId);
    		permMap.put("permState", permState);
    		qbuilder.put("permFilter", permMap);
    	}
        List<ApiMethod> list = new ArrayList<ApiMethod>();
        int total = apiMethodService.getTotalRows(qbuilder);
        if (total > 0) {
        	list = apiMethodService.find(null, qbuilder, null);
        	List<Long> apiIds = new ArrayList<Long>();
        	List<Long> dbIds = new ArrayList<Long>();
        	for (ApiMethod obj : list) {
				apiIds.add(obj.getId());
				dbIds.add(obj.getDbId());
			}
        	Map<Long, DbInfo> dbInfoMap = new HashMap<Long, DbInfo>();
        	if (dbIds != null) {
				List<DbInfo> dbInfoList = dbInfoService.find(null, dbInfoService.initQbuilder("ids", dbIds), null);
				for (DbInfo dbInfo : dbInfoList) {
					dbInfoMap.put(dbInfo.getId(), dbInfo);
				}
			}
        	Map<String, Object> permQbuider = new HashMap<String, Object>();
        	permQbuider.put("apiUserId", apiUserId);
        	permQbuider.put("apiIds", apiIds);
        	List<ApiPerm> apiPermList = apiPermService.find(null, permQbuider, null);
        	Map<Long, ApiPerm> apiPermMap = new HashMap<Long, ApiPerm>();
        	List<Long> hasPermApiIds = new ArrayList<Long>();
        	for (ApiPerm apiPerm : apiPermList) {
        		hasPermApiIds.add(apiPerm.getApiId());
        		apiPermMap.put(apiPerm.getApiId(), apiPerm);
			}
        	for (ApiMethod obj : list) {
				if (hasPermApiIds.contains(obj.getId())) {
					obj.setShow_apiUserPermState(1);
					if (obj.getAddQuerySqlRequired() == null ||obj.getAddQuerySqlRequired()!=1) {
						obj.setShow_apiUserSelectPermState(1);
					} else {
						Integer show_apiUserSelectPermState = 0;
						ApiPerm apiPerm = apiPermMap.get(obj.getId());
						if (apiPerm != null) {
							if ((apiPerm.getQueryAll() != null && apiPerm.getQueryAll() == 1) || StringUtils.isNotBlank(apiPerm.getAddQuerySql())) {
								show_apiUserSelectPermState = 1;
							}
						}
						obj.setShow_apiUserSelectPermState(show_apiUserSelectPermState);
					}
				} else {
					obj.setShow_apiUserPermState(0);
					obj.setShow_apiUserSelectPermState(0);
				}
				if (obj.getDbId() != null && dbInfoMap.containsKey(obj.getDbId())) {
					obj.setShow_dbName(dbInfoMap.get(obj.getDbId()).getName());
				}
			}
		}
        return SRemoteResult.initPageList(list, total);
    }
    

}
